<?php
namespace app\api\controller;

use app\common\model\Article as P;
use app\common\model\Comment;
use app\common\validate\Post as postValidate;
use think\exception\ValidateException;
use think\facade\Db;

class Article extends Base
{
    //轮播图文章/置顶文章
    public function getConfigPost()
    {
        // carousel or topArticle
        $config = input("config");
        $carouselConfig = Db::name("system")->where("config","carousel")->value("value");
        $carouselArticle = Db::name("article")->field("id,title,cover_image")->where("status",0)->where("id","in", $carouselConfig)->select()->toArray();

        foreach ($carouselArticle as $key =>$item){
            if (strpos($item["cover_image"],"http") === false){
                if (empty($item["cover_image"])){
                    $carouselArticle[$key]["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
                }else{
                    $carouselArticle[$key]["cover_image"] = request()->domain() .$item["cover_image"];
                }
            }
        }
        return json($carouselArticle);
    }

    public function followUserArticle()
    {
        $sessionKey = input("sessionKey");
        if (empty($sessionKey)){
            return json(["code" => 0 ,"sessionKey为空"]);
        }
        $uid = $this->getUid($sessionKey);
        $followUids = Db::name("follow")->where("uid",$uid)->column("follow_uid");
        $where[] = array("uid","in",$followUids);
        $list = $this->SQLArticle($where);
        return json($list);
    }

    public function postAdd()
    {
        $data = input("post.");
        $data["status"] = 1;

        if ($this->checkText( $data["content"]) != 0){
            return json(["code" => 0 ,"msg" =>"内容违法违规"]);
        }
        if ($this->checkText( $data["title"]) != 0){
            return json(["code" => 0 ,"msg" =>"内容违法违规"]);
        }
        $order=array("\r\n","\n","\r");
        $replace='<br/>';
        $data["content"]=str_replace($order,$replace,$data["content"]);

        try {
            validate(postValidate::class)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return json(["code" => 0,"msg" =>$e->getError()]);
        }

        preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',input("content","","trim"), $ereg);//正则表达式把图片的SRC获取出来了
        if(empty($ereg)) {
            $cover_image = "";
        }else{
            $cover_image = $ereg[1];//图片SRC
        }
        $data["cover_image"] = $cover_image;
        $data["uid"] = $this->getUid($data["sessionKey"]);
        $create = P::create($data);
        if ($create){
            return json(["code" => 1,"msg" =>"投稿成功，待管理员审核","postId" => $create->id]);
        }
        return json(["code" => 0,"msg" =>"投稿失败"]);
    }

    //文章列表
    public function newList()
    {
        $cateId = input('cateId');
        $sessionKey = input("sessionKey");
        if (!empty($sessionKey)){
            $uid = $this->getUid($sessionKey);
            $where["uid"] = $uid;
        }else{
            $where["status"] = 0;
        }

        if ($cateId > 0){
            $where["cate_id"] = $cateId;
        }

        $list = $this->SQLArticle($where);
        return json($list);
    }

    public function SQLArticle($where)
    {
        $list = Db::name('article')->withoutField("content")->order("id desc")->where($where)->paginate(10,false,['query'=>request()->param()])->each(function($item, $key){
            $item["userInfo"] = Db::name("user")->field("username,avatar")->where("uid",$item["uid"])->find();
            $item["commentSum"] = Db::name("comment")->where("aid",$item["id"])->where("type",1)->count();
            $item["fabulous"] = Db::name("fabulous")->where("aid",$item["id"])->where("type",1)->count();
            if (empty($item["cover_image"])){
                $item["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
            }
            return $item;
        });
        return $list;
    }


    //文章详情
    public function detail()
    {
        $id = input('id');
        Db::name('article')->where('id',$id)->inc('read_count')->update();
        $detail = P::withJoin(['userInfo' => ['username','uid','avatar','intro'],'cate' =>['cate_name']])->where('id',$id)->find();
        $comment = Comment::withJoin(['userInfo' => ['username','avatar']])->order("id desc")->where("type",1)->where("aid",$id)->select();
        $detail["comment"] = $comment;
        if (!$detail){
            return json(["code" => 0,"msg" => "没有该文章"]);
        }
        if (strpos($detail["cover_image"],"http") === false){
            if (empty($detail["cover_image"])){
                $detail["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
            }else{
                $detail["cover_image"] = request()->domain() .$detail["cover_image"];
            }
        }
        return json($detail);
    }

    //分类列表
    public function cateList()
    {
        $list = Db::name("category")->select()->toArray();
        
        foreach ($list as $key =>$item){
            if (empty($item["cover_image"])){
                $list[$key]["cover_image"] = request()->domain() ."/static/images/api/default_cate_cover.jpg";
            }
        }

        return json($list);
    }

    public function myCollectArticle()
    {
        $sessionKey = input("sessionKey");
        if (empty($sessionKey)){
            return json(["code" => 0 ,"sessionKey为空"]);
        }
        $uid = $this->getUid($sessionKey);
        $where["uid"] = $uid;
        $postIds = Db::name("article_collection")->where($where)->column("post_id");

        $list = Db::name('article')->withoutField("content")->where("id","in",$postIds)->order("id desc")->paginate(10,false,['query'=>request()->param()])->each(function($item, $key){
            $item["userInfo"] = Db::name("user")->field("username,avatar")->where("uid",$item["uid"])->find();
            $item["commentSum"] = Db::name("comment")->where("aid",$item["id"])->count();
            $item["fabulous"] = Db::name("fabulous")->where("aid",$item["id"])->count();
            if (empty($item["cover_image"])){
                $item["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
            }
            return $item;
        });

        return json($list);
    }

    /**
     * 是否收藏
     *
     **/
    public function isCollection()
    {
        $sessionKey = input("sessionKey");
        if (empty($sessionKey)){
            return json(["code" => "error" ,"sessionKey为空"]);
        }
        $uid = $this->getUid($sessionKey);
        $aid = input("id");
        $where["uid"] = $uid;
        $where["post_id"] = $aid;
        $where[" type"] = input("type");
        $res = Db::name("article_collection")->where($where)->find();
        if ($res){
            return json(["code" => 0, "msg" => "已收藏"]);
        }
        return json(["code" => 1, "msg" => "未收藏"]);
    }

    public function addCollection()
    {
        $sessionKey = input("sessionKey");
        if (empty($sessionKey)){
            return json(["code" => 0 ,"sessionKey为空"]);
        }
        $uid = $this->getUid($sessionKey);
        $aid = input("id");
        $data["uid"] = $uid;
        $data["post_id"] = $aid;
        $data["type"] = input("type");
        $isCollection =  $res = Db::name("article_collection")->where($data)->find();
        if ($isCollection){
            return json(["code" => 0, "msg" => "请勿重复收藏"]);
        }
        $res = Db::name("article_collection")->insert($data);

        if ($res){
            return json(["code" => 1 ,"msg" => "收藏成功"]);
        }
        return json(["code" => 0 ,"msg" => "收藏失败"]);
    }

    public function cancelCollection()
    {
        $sessionKey = input("sessionKey");
        if (empty($sessionKey)){
            return json(["code" => 0 ,"sessionKey为空"]);
        }
        $uid = $this->getUid($sessionKey);
        $aid = input("id");
        $where["uid"] = $uid;
        $where["post_id"] = $aid;
        $where[" type"] = input("type");
        $res = Db::name("article_collection")->where($where)->delete();

        if ($res){
            return json(["code" => 1 ,"msg" => "已取消收藏"]);
        }
        return json(["code" => 0 ,"msg" => "取消收藏失败"]);
    }

    /**
     * 是否喜欢文章
     *
     **/
    public function isLike()
    {
        $sessionKey = input("sessionKey");
        if (empty($sessionKey)){
            return json(["code" => "error" ,"sessionKey为空"]);
        }
        $uid = $this->getUid($sessionKey);
        $aid = input("id");
        $where["uid"] = $uid;
        $where["aid"] = $aid;
        $where[" type"] = input("type");
        $res = Db::name("fabulous")->where($where)->find();
        if ($res){
            return json(["code" => 0, "msg" => "已喜欢"]);
        }
        return json(["code" => 1, "msg" => "未喜欢"]);
    }

    public function addLike()
    {
        $sessionKey = input("sessionKey");
        if (empty($sessionKey)){
            return json(["code" => 0 ,"sessionKey为空"]);
        }
        $uid = $this->getUid($sessionKey);
        $aid = input("id");
        $data["uid"] = $uid;
        $data["aid"] = $aid;
        $data["type"] = input("type");
        $isCollection =  $res = Db::name("fabulous")->where($data)->find();
        if ($isCollection){
            return json(["code" => 0, "msg" => "请勿重复喜欢"]);
        }
        $res = Db::name("fabulous")->insert($data);

        if ($res){
            return json(["code" => 1 ,"msg" => "喜欢成功"]);
        }
        return json(["code" => 0 ,"msg" => "喜欢失败"]);
    }

    public function cancelLike()
    {
        $sessionKey = input("sessionKey");
        if (empty($sessionKey)){
            return json(["code" => 0 ,"sessionKey为空"]);
        }
        $uid = $this->getUid($sessionKey);
        $aid = input("id");
        $where["uid"] = $uid;
        $where["aid"] = $aid;
        $where[" type"] = input("type");

        $res = Db::name("fabulous")->where($where)->delete();

        if ($res){
            return json(["code" => 1 ,"msg" => "已取消喜欢"]);
        }
        return json(["code" => 0 ,"msg" => "取消喜欢失败"]);
    }
}